<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * Complete Interaction of the measures
 *
 * @author febusch
 * 
 *
 * 28.11.2012 Migration to Gas ORM by lukas
 *
 *
 */
class Training extends TMT_Controller {

    function __construct() {
        parent::__construct();

        $this->load->helper('url', 'input', 'form');
        $this->load->library('datepicker');
    }

    public function index() {
        $this->headline = 'Übersicht über alle aktuellen Schulungsmassnahmen';
        // overview erstellen
        $this->view_data['trainings'] = Model\Training::with('place, employee')->all();

        foreach ($this->view_data['trainings'] as $training) {
            $this->view_data['amount_participants'][$training->id] = count($training->employee());
        }
    }

    public function create() {
        $course_id = $this->input->post('course_id');

        if ($course_id) {

            // get course data and trainingstatus id
            $participants = Model\Course::find($course_id)->employee();
            if (!empty($participants)) {
                $trainingsstatus = Model\Trainingstatus::find_by_name('Schwebend', FALSE);
                if (is_null($trainingsstatus)) {
                    $this->display_error('Error', 'Standard Trainingsstatus nicht eingetragen!');
                    return;
                }

                $data = array('course_id' => $course_id);
                $traininggroup = Model\Traininggroup::make($data);
                $traininggroup->save();
                $traininggroup->id = Model\Traininggroup::last_created()->id;

                
               
                // create new training object
                $training = new Model\Training();
                $training->trainingstatus_id = $trainingsstatus->id;
                $training->traininggroup_id = $traininggroup->id;
                $training->save();


                // get id of last created object
                $training_id = Model\Training::last_created()->id;

                foreach ($participants as $participant) {
                    $p = new Model\Employee\Training();
                    $p->employee_id = $participant->id;
                    $p->training_id = $training_id;
                    $p->save();
                }
            redirect('/training');
            }
            else
            {
                $this->display_error("Kein Bedarf vorhanden!", "Achtung: Es ist kein Bedarf vorhanden!", "error");
            }

        }
    }

    public function confirm($course_id = FALSE) {
        if ($course_id) {
            $this->view_data['course'] = Model\Course::with('team', 'contactdata', 'place', 'participant')->find($course_id);
            $this->view_data['participants'] = $this->view_data['course']->participant();
            $this->view_data['location'] = $this->input->post('location');
            $this->view_data['loc_conflict'] = $this->session->flashdata('loc_conflict');

            $this->session->set_flashdata('CourseID', $course_id);
            $this->session->set_flashdata('Location', $this->input->post('location'));
            $this->session->set_flashdata('Date', $this->datepicker->get_values('%Y-%m-%d %H:%M:%S'));
        }

        $this->headline = 'Eine neue Maßnahme erstellen - Zusammenfassung';
    }
    
    public function details($trainingID = FALSE) {
    	    	
    	$this->view_data['data']['active_user'] = $this->employee;
        /*  possible values for <display>
         *   'box'   => show attendees in boxes
         *   'list'  => show attendees in a list
         */
        $this->view_data['data']['display'] = $this->input->get('display');

        /*  possible values for <edit>
         *   'cost'    => adds a form to the infotable allowing the user to add a cost entry
         *   'dummy'   => dummy dummy dummy
         */
        $this->view_data['data']['edit'] = $this->input->get('edit');
        $this->view_data['data']['training'] = Model\Training::with('employee, 
                                                                        contactdata, 
                                                                        place, 
                                                                        traininggroup, 
                                                                        cost, 
                                                                        costtype,
                                                                        trainingstatus,
                                                                        ')->find($trainingID);
        $this->view_data['data']['status'] = array('Schwebend' => 'blue',
            'Festgelegt' => 'cyan',
            'Geschlossen' => 'black',
            'Gebucht' => 'orange',
            'Storniert' => 'red',
            'Fakturiert' => 'green',
        );
        $participants = $this->view_data['data']['training']->employee();

        $this->view_data['one_answered'] = FALSE;
        
        if ($this->view_data['data']['training']->trainingstatus()->name != 'Schwebend') {
            
            foreach ($participants as $participant) {
                /**
                 * @todo: nicht like! lieber where
                 */
                $conf = Model\Confirmation::like('training_id', $trainingID)->find_by_employee_id($participant->id, FALSE);

                /*  $conf => Confirmation status
                 *   0 = declined
                 *   1 = accepted
                 *   2 = no answer yet
                 */
                if (is_null($conf))
                {
                    $participant->confirmation = 2;
                }
                else
                {
                    $participant->confirmation = (int) $conf->confirmed;
                    $participant->confirmed_at = $conf->metadata()->created;
                    $this->view_data['one_answered'] = TRUE;
                }

                $this->view_data['data']['participants'][] = $participant;
            }
        }
        else
            $this->view_data['data']['participants'] = $participants;

        /*  store costtypes for later use in a dropdown selection,
         *   we need them if the user wants to add a cost
         */
        if ($this->view_data['data']['edit'] == 'cost') {
            // fetch costtype objects
            $costtypes = Model\Costtype::all();

            foreach ($costtypes as $costtype) {
                $this->view_data['data']['costtypes'][$costtype->id] = $costtype->name;
            }
        }

        // initialize this array here to prevent -array_key_exists- from throwing errors
        $this->view_data['data']['locations'] = array();

        /*  iterate trough participants and create location distribution array like this:
         *   array(
         *       'Darmstadt' => 3,
         *       'Bonn'      => 2,
         *   );
         */
        foreach ($this->view_data['data']['participants'] as $employee) {
            $city = $employee->contactdata()->place()->city;
            if (array_key_exists($city, $this->view_data['data']['locations']))
                $this->view_data['data']['locations'][$city]++;
            else
                $this->view_data['data']['locations'][$city] = 1;
        }

        $this->headline = 'Maßnahmedetails #' . $trainingID;
    }

    # needs some fixin
    #
    /*public function do_it() {
        $this->load->model('data_management/measure_model');

        $ft_id = $this->session->flashdata('FachthemenID');
        $loc = $this->session->flashdata('Standort');
        $date = $this->session->flashdata('Termin');
        $memb = $this->session->flashdata('Members');

        if ($ft_id AND $loc AND $date AND $memb) {
            if ($this->measure_model->create_measure($ft_id, $loc, $date, $memb))
                $this->display_error('Erfolg', 'Maßnahme wurde erfolgreich erstellt!', 'success');
            else {
                $this->display_error('Ein Fehler ist aufgetreten', 'Maßnahme konnte nicht erstellt werden!');
            }
        }
    }*/

    # needs some fixin
    #
    /*public function edit($trainingID = FALSE) {
        if ($trainingID) {
            $new_status = $this->input->post('status_select');
            if ($new_status) {
                $this->measure_model->update_status($new_status, $trainingID);
            }
        }
        redirect('/measure/details/' . $trainingID);
    }*/

    public function edit_members($measureID = FALSE) {
        $to_add = $this->input->post('member_add'); // Array von hinzuzufügenden Teilnehmern
        $to_del = $this->input->post('member_del'); // Array von zu löschenden Teilnehmern
        var_dump($to_del);

        if ($to_add) {
            $this->measure_model->create_relations_mitarbeiter_smassnahme($measureID, $to_add);
        } elseif ($to_del) {
            $this->measure_model->delete_relations_mitarbeiter_smassnahme($measureID, $to_del);
        }

        redirect('/measure/details/' . $measureID . '?mode=edit');
    }

    /**
     * 
     * @param int $trainingID
     * @param string $target
     */
    public function do_upload($trainingID = FALSE){
        $this->lang->load('upload', 'deutsch');
        $this->load->model('attach_model');
        
        $target = $this->input->get('target');
        $this->attach_model->upload_file('all', 'tmp', $target.'/'.$trainingID);
    }


    public function facturize_training($trainingID = FALSE){
    	if(!$trainingID || !$this->employee->is_management()) {
    		redirect('/training/');
    	}
    	 
        #adjusts training status to 'fakturiert'

        $training = Model\Training::find($trainingID);

        $this->headline = 'Nächster Status: "Fakturiert"';
        $this->view_data['trainingID'] = $trainingID;
        $this->view_data['upload_error'] = $this->session->flashdata('upload_error');
        
        // Ist was hochgeladen worden, dann steckt hier ein array drin
        $attachment = $this->session->flashdata('attachment');
        
        if($attachment)
        {
            $this->load->model('attach_model');
            $this->attach_model->move_attachment($attachment['filename'], 'bills');
            $attachmentID = $this->attach_model->insert_attachment('bills/'.$attachment['filename']);

            // Set new Attributes
            $training->bill_id = $attachmentID;
            $training->set_status(5);
            $training->save();

            redirect('training/details/'.$trainingID);
        }     
    }
	
    public function close_training($trainingID = FALSE){
    	if(!$trainingID || !$this->employee->is_management()) {
    		redirect('/training/');
    	}
    	
    	
        $training       = Model\Training::with('employee')->find($trainingID);
        $traininggroup  = Model\Traininggroup::with('survey,
                                                     training,')->find($training->traininggroup_id);
        $trainings_alt  = $traininggroup->training();
        $course_id      = $traininggroup->course_id;

        #temporarily disable other spawns of the selected training
        if (sizeof($trainings_alt) > 1){
            foreach ($trainings_alt as $training_unit) {
                if ($training_unit->id != $trainingID){
                    $training_unit->canceled = 1;
                    $training_unit->save();
                }
            }
        }

        #modify stopedemand of accepted attendees
        $users = $training->employee();
        foreach ($users as $user) {
            $stopedemands = $user->stopedemand();                   #
            foreach ($stopedemands as $stopedemand) {               #
                if ($stopedemand->course_id == $course_id){         #
                    break;                                          # I guess this isn't working!
                }                                                   #
            }
            $stopedemand->status = 1;
            $stopedemand->save();
            unset($stopedemand);
        }

        #cleanup survey data
        $surveys = $traininggroup->survey();
        foreach ($surveys as $survey) {
            $survey->delete();
        }

        $training->set_status(3);

        redirect('/training/details/' . $trainingID);
    }

    public function book_training($trainingID = FALSE){
    	
    	if(!$trainingID || !$this->employee->is_management()) {
    		redirect('/training/');
    	}
    	
                
        $training = Model\Training::find($trainingID);
        
        // Wenn bereits ne offer angehängt wurde...
        if(!is_null($training->offer()))
        {
            $this->display_error ('Fehler',
                                  'Achtung: Es wurde bereits eine Datei angehängt!<br > 
                                   Wenn sich der Status aktuell in Geschlossen befindet, besteht eine Dateninkonsitenz.<br >
                                   Benachrichtigen Sie den Administrator!',
                                   'danger');
        }
            //redirect ('training/details/'.$trainingID);
        else
        {
            $this->headline = 'Nächster Status: "Bestellt"';
            $this->view_data['trainingID'] = $trainingID;
            
            $this->view_data['cartNr'] = $this->session->flashdata('cartNr');
            $this->view_data['upload_error'] = $this->session->flashdata('upload_error');
            
            // Ist was hochgeladen worden, dann steckt hier ein array drin
            $attachment = $this->session->flashdata('attachment');
            
            if($attachment)
                $this->view_data['attachment'] = $attachment;
        }     
    }
    
    public function book_training_submit() {
        $filename = $this->input->post('filename');
        $trainingID = $this->input->post('trainingID');
        $cartNr = $this->input->post('cartNr');
        
        // Get the right object
        $training = Model\Training::find($trainingID);
        
        $this->load->model('attach_model');
        $this->attach_model->move_attachment($filename, 'offers');
        $attachmentID = $this->attach_model->insert_attachment('offers/'.$filename);

        // Set new Attributes
        $training->offer_id = $attachmentID;
        $training->cart_number = $cartNr;
        $training->set_status(4);
        $training->save();
        
        redirect('training/details/'.$trainingID);   
    }


    
    # do we still need this function?
    public function validate_offer($trainingID = FALSE){
        #validates the uploaded file and redirects accordingly
        $config['upload_path']      = './uploads/offers/';
        $config['allowed_types']    = 'pdf|doc|docx|txt|rtf';
        $config['max_size']         = '500';
        $config['encrypt_name']     = TRUE;

        $this->load->library('upload', $config);

        if (!$this->upload->do_upload()){
            $error = array('error' => $this->upload->display_errors());
            redirect('/training/upload_bill/' . $trainingID);
        }
        else {
            $upload_data = $this->upload->data();
            $filename    = $upload_data['file_name'];
            $success     = 'Datei wurde erfolgreich erfasst.';
            redirect('/training/book_training/' . $trainingID);
        }
    }

    public function exclude_member($id = FALSE) {
//        if($id)
//        {
//            $members = $this->session->userdata('measure_members');
//            foreach($members as $member)
//            {
//                if($member->persnr != $id)
//                {
//                    $new_data[] = $member;
//                }
//            }
//            $this->session->unset_userdata('measure_members');
//            $this->session->set_userdata('measure_members', $new_data);
//        }
//        
//        $this->session->keep_flashdata('location');

        redirect('/measure/confirm/' . $this->session->flashdata('measureid'));
    }

    private function _validate_exclude() {
        echo $this->input->get('exclude');
    }

    public function add_details($training_id = FALSE) {
        if (!$training_id || !$this->employee->is_management())
            redirect('training');

        $this->load->helper('date');

        $this->headline = 'Termine und Orte';
        $this->show_sidebar = FALSE;

        $this->view_data['data']['training'] = Model\Training::with('employee, contactdata, place')->find($training_id);

        $attendees = $this->view_data['data']['training']->employee();


        //Get Places
        $places = array();
        foreach ($attendees as $attendee) {
            $places[] = $attendee->contactdata()->place();
        }

        $this->view_data['places_arr'] = array();
        foreach ($places as $place) {
            $this->view_data['places_arr'][$place->id] = $place->city;
        }


        //Get Trainer 
        $trainer_type = Model\Contacttype::find_by_name('Trainer', FALSE)->id;
        $trainers = Model\Contactdata::find_by_contacttype_id($trainer_type, TRUE);

        $this->view_data['trainer_arr'] = array();
        foreach ($trainers as $trainer) {
            $this->view_data['trainer_arr'][$trainer->id] = $trainer->surname . ', ' . $trainer->forename;
        }
    }

    public function add_cost($training_id = FALSE) {
        if (!$training_id)
            redirect('training/details');

        // get traininggroup
        $traininggroup = Model\Training::find($training_id)->traininggroup();
        $costtype_id = $this->input->post('costtype');

        // create new cost record
        $cost = new Model\Cost;
        $cost->amount = $this->input->post('cost-amount');
        $cost->costtype_id = $costtype_id;

        $cost->with('Traininggroup\Cost')->save();
        $cost->id = Model\Cost::last_created()->id;

        $data = array('traininggroup_id' => $traininggroup->id, 'cost_id' => $cost->id);

        $traininggroup_cost = Model\Traininggroup\Cost::make($data);
        $test = $traininggroup_cost->save(TRUE);

        redirect('training/details/' . $training_id);
    }

    public function add_details_submit() {
    	if(!$this->employee->is_management()) {
    		redirect('/training/');
    	}
    	
        $this->load->library('form_validation');

        $this->form_validation->set_rules('submit', 'Button', 'required');
        $this->form_validation->set_rules('max_attendees', 'Teilnehmerzahl', 'required|numeric');
        $this->form_validation->set_rules('place_id', 'Standort', 'required|numeric');
        $this->form_validation->set_rules('trainer_id', 'Trainer', 'required|numeric');
        $this->form_validation->set_rules('training_id', 'Training', 'required|numeric');


        $this->form_validation->set_rules('termin[1][date][from]', 'Datum - Von', 'required');
        $this->form_validation->set_rules('termin[1][date][till]', 'Datum - Bis', 'required');
        $this->form_validation->set_rules('termin[1][time][from][minute]', 'Zeit von Minute', 'required');
        $this->form_validation->set_rules('termin[1][time][from][hour]', 'Zeit von Stunde', 'required');
        $this->form_validation->set_rules('termin[1][time][till][minute]', 'Zeit bis Minute', 'required');
        $this->form_validation->set_rules('termin[1][time][till][hour]', 'Zeit bis Stunde', 'required');
        $this->form_validation->set_rules('termin[1][date][deadline]', 'Deadline', 'required');


        $this->view_data['termin1'] = $this->form_validation->run();

        if (!$this->view_data['termin1']) {
            if (isset($_POST['training_id']) AND set_value('training_id') != '')
                redirect('training/add_details/' . set_value('training_id'));
            else
                redirect('training');
        }


        $this->form_validation->set_rules('termin[2][date][from]', 'Datum - Von', 'required');
        $this->form_validation->set_rules('termin[2][date][till]', 'Datum - Bis', 'required');
        $this->form_validation->set_rules('termin[2][time][from][minute]', 'Zeit von Minute', 'required');
        $this->form_validation->set_rules('termin[2][time][from][hour]', 'Zeit von Stunde', 'required');
        $this->form_validation->set_rules('termin[2][time][till][minute]', 'Zeit bis Minute', 'required');
        $this->form_validation->set_rules('termin[2][time][till][hour]', 'Zeit bis Stunde', 'required');
        $this->form_validation->set_rules('termin[2][date][deadline]', 'Deadline', 'required');

        $this->view_data['termin2'] = $this->form_validation->run();


        $this->form_validation->set_rules('termin[3][date][from]', 'Datum - Von', 'required');
        $this->form_validation->set_rules('termin[3][date][till]', 'Datum - Bis', 'required');
        $this->form_validation->set_rules('termin[3][time][from][minute]', 'Zeit von Minute', 'required');
        $this->form_validation->set_rules('termin[3][time][from][hour]', 'Zeit von Stunde', 'required');
        $this->form_validation->set_rules('termin[3][time][till][minute]', 'Zeit bis Minute', 'required');
        $this->form_validation->set_rules('termin[3][time][till][hour]', 'Zeit bis Stunde', 'required');
        $this->form_validation->set_rules('termin[3][date][deadline]', 'Deadline', 'required');

        $this->view_data['termin3'] = $this->form_validation->run();


        $this->view_data['data']['training'] = Model\Training::with('employee, contactdata, place')->find(set_value('training_id'), FALSE);

        $attendees = $this->view_data['data']['training']->employee();


        $places = array();
        foreach ($attendees as $attendee) {
            $places[] = $attendee->contactdata()->place();
        }

        $this->view_data['places_arr'] = array();
        foreach ($places as $place) {
            $this->view_data['places_arr'][$place->id] = $place->city;
        }

        //Get Trainer
        $trainer_type = Model\Contacttype::find_by_name('Trainer', FALSE)->id;
        $trainer = Model\Contactdata::find_by_contacttype_id($trainer_type, TRUE);

        $this->view_data['trainer_arr'] = array();
        foreach ($trainer as $item) {
            $this->view_data['trainer_arr'][$item->id] = $item->surname . ', ' . $item->forename;
        }



        $this->headline = 'Bestätigen Sie Ihre Eingabe!';
    }

    public function insert_details() {
        $this->load->library('form_validation');

        $this->form_validation->set_rules('submit', 'Button', 'required');
        $this->form_validation->set_rules('max_attendees', 'Teilnehmerzahl', 'required|numeric');
        $this->form_validation->set_rules('place_id', 'Standort', 'required|numeric');
        $this->form_validation->set_rules('trainer_id', 'Trainer', 'required|numeric');
        $this->form_validation->set_rules('training_id', 'Training', 'required|numeric');


        $this->form_validation->set_rules('termin[1][date][from]', 'Datum - Von', 'required');
        $this->form_validation->set_rules('termin[1][date][till]', 'Datum - Bis', 'required');
        $this->form_validation->set_rules('termin[1][time][from][minute]', 'Zeit von Minute', 'required');
        $this->form_validation->set_rules('termin[1][time][from][hour]', 'Zeit von Stunde', 'required');
        $this->form_validation->set_rules('termin[1][time][till][minute]', 'Zeit bis Minute', 'required');
        $this->form_validation->set_rules('termin[1][time][till][hour]', 'Zeit bis Stunde', 'required');
        $this->form_validation->set_rules('termin[1][date][deadline]', 'Deadline', 'required');


        $this->view_data['termin1'] = $this->form_validation->run();

        if (!$this->view_data['termin1']) {
            /*
              if(isset($_POST['training_id']) AND set_value('training_id') != '')
              //redirect('training/add_details/' . set_value('training_id'));
              else
              redirect('training');
             */
            echo validation_errors();
        }


        $this->form_validation->set_rules('termin[2][date][from]', 'Datum - Von', 'required');
        $this->form_validation->set_rules('termin[2][date][till]', 'Datum - Bis', 'required');
        $this->form_validation->set_rules('termin[2][time][from][minute]', 'Zeit von Minute', 'required');
        $this->form_validation->set_rules('termin[2][time][from][hour]', 'Zeit von Stunde', 'required');
        $this->form_validation->set_rules('termin[2][time][till][minute]', 'Zeit bis Minute', 'required');
        $this->form_validation->set_rules('termin[2][time][till][hour]', 'Zeit bis Stunde', 'required');
        $this->form_validation->set_rules('termin[2][date][deadline]', 'Deadline', 'required');

        $this->view_data['termin2'] = $this->form_validation->run();


        $this->form_validation->set_rules('termin[3][date][from]', 'Datum - Von', 'required');
        $this->form_validation->set_rules('termin[3][date][till]', 'Datum - Bis', 'required');
        $this->form_validation->set_rules('termin[3][time][from][minute]', 'Zeit von Minute', 'required');
        $this->form_validation->set_rules('termin[3][time][from][hour]', 'Zeit von Stunde', 'required');
        $this->form_validation->set_rules('termin[3][time][till][minute]', 'Zeit bis Minute', 'required');
        $this->form_validation->set_rules('termin[3][time][till][hour]', 'Zeit bis Stunde', 'required');
        $this->form_validation->set_rules('termin[3][date][deadline]', 'Deadline', 'required');

        $this->view_data['termin3'] = $this->form_validation->run();

        $status_id = Model\Trainingstatus::find_by_name('Festgelegt', FALSE)->id;

        //Set the first appointment
        $temp_place = Model\Place::find(set_value('place_id'));

        $place = new Model\Place();
        $place->city = $temp_place->city;
        $place->save();
        $place->id = Model\Place::last_created()->id;



        $training = Model\Training::find(set_value('training_id'));

        $date_from = explode('.', set_value('termin[1][date][from]'), 3);
        $date_to = explode('.', set_value('termin[1][date][till]'), 3);

        $training->appointment_from = $date_from[2] . '-' . $date_from[1] . '-' . $date_from[0] . ' ' . set_value('termin[1][time][from][hour]') . ':' . set_value('termin[1][time][from][minute]') . ':00';
        $training->appointment_to = $date_to[2] . '-' . $date_to[1] . '-' . $date_to[0] . ' ' . set_value('termin[1][time][till][hour]') . ':' . set_value('termin[1][time][till][minute]');
        //$training->survey_from		= date("Y-m-d");
        //$training->survey_to		= set_value('termin[1][date][deadline]');
        $training->place_id = $place->id;
        $training->trainingstatus_id = $status_id;

        $traininggroup = $training->traininggroup();
        $traininggroup->max_participants = set_value('max_attendees');
        $traininggroup->contactdata_id = set_value('trainer_id');
        $traininggroup->save();

        $training->save();

        //2nd Appointment
        if ($this->view_data['termin2']) {
            $place = new Model\Place();
            $place->city = $temp_place->city;
            $place->save();
            $place->id = Model\Place::last_created()->id;

            $date_from = explode('.', set_value('termin[2][date][from]'), 3);
            $date_to = explode('.', set_value('termin[2][date][till]'), 3);

            $training = new Model\Training();
            $training->appointment_from = $date_from[2] . '-' . $date_from[1] . '-' . $date_from[0] . ' ' . set_value('termin[2][time][from][hour]') . ':' . set_value('termin[2][time][from][minute]') . ':00';
            $training->appointment_to = $date_to[2] . '-' . $date_to[1] . '-' . $date_to[0] . ' ' . set_value('termin[2][time][till][hour]') . ':' . set_value('termin[2][time][till][minute]');
            $training->place_id = $place->id;
            $training->trainingstatus_id = $status_id;
            $training->traininggroup_id = $traininggroup->id;

            if (!$training->save()) {
                //FEHLER
            }
            else
                $training2 = Model\Training::last_created()->id;
        }

        if ($this->view_data['termin3']) {
            $place = new Model\Place();
            $place->city = $temp_place->city;
            $place->save();
            $place->id = Model\Place::last_created()->id;

            $date_from = explode('.', set_value('termin[3][date][from]'), 3);
            $date_to = explode('.', set_value('termin[3][date][till]'), 3);

            $training = new Model\Training();
            $training->appointment_from = $date_from[2] . '-' . $date_from[1] . '-' . $date_from[0] . ' ' . set_value('termin[3][time][from][hour]') . ':' . set_value('termin[3][time][from][minute]') . ':00';
            $training->appointment_to = $date_to[2] . '-' . $date_to[1] . '-' . $date_to[0] . ' ' . set_value('termin[3][time][till][hour]') . ':' . set_value('termin[3][time][till][minute]');

            $training->place_id = $place->id;
            $training->trainingstatus_id = $status_id;
            $training->traininggroup_id = $traininggroup->id;

            if (!$training->save()) {
                //FEHLER
            }
            else
                $training3 = Model\Training::last_created()->id;
        }

        $attendees = Model\Training::find(set_value('training_id'))->employee();

        foreach ($attendees as $attendee) {
            if (isset($training2)) {
                $employee_training = new Model\Employee\Training();
                $employee_training->employee_id = $attendee->id;
                $employee_training->training_id = $training2;
                $employee_training->save();
            }

            if (isset($training3)) {
                $employee_training = new Model\Employee\Training();
                $employee_training->employee_id = $attendee->id;
                $employee_training->training_id = $training3;
                $employee_training->save();
            }
        }

        $training = Model\Training::find(set_value('training_id'));
        
        $data = $this->_create_surveys($training, set_value('termin[1][date][deadline]'));
        
        if (!$this->_send_survey($data))
            echo 'Mail funzt nicht!';
        else
            redirect('training');
    }

    public function kill_training($training_id = FALSE) {
        if ($training_id) {
            $status_id = Model\Trainingstatus::find_by_name('Storniert', FALSE)->id;

            $training = Model\Training::find($training_id);

            $training->trainingstatus_id = $status_id;
            $training->save();
        }

        redirect('training');
    }

    private function _create_surveys($training, $deadline) {
        if (is_null($training) || is_null($deadline)) {
            return FALSE;
        }

        $employees = $training->employee();
        $trainingroup = $training->traininggroup();


        $charPool = '0123456789abcdefghijklmnopqrstuvwxyz';


        foreach ($employees as $employee) {
            $survey = new Model\Survey();
            $survey->traininggroup_id = $trainingroup->id;
            $survey->employee_id = $employee->id;

            $result = "";
            for ($p = 0; $p < 15; $p++)
                $result .= $charPool[mt_rand(0, strlen($charPool) - 1)];

            $survey->id = hash("sha256", $result);
            $survey->survey_to = date("Y-m-d", strtotime($deadline));
            $survey->save();
            $data[] = $survey;
        }

        return $data;
    }

    private function _send_survey($surveys) {

        require_once(BASEPATH . '../application/plugins/' . "phpmailer/class.phpmailer.php");
                    
        if (!defined('SMART_HOST'))
            define('SMART_HOST', 'administrator@mail1.gdc-bln01.t-systems.com');

        foreach ($surveys as $survey) {

            $mail = new PHPMailer();

            $mail->IsSMTP();
            $mail->IsHTML();

            $mail->Host = "mail1.gdc-bln01.t-systems.com";
            $mail->SMTPAuth = false;

            $mail->FromName = "TMT Admin";
            $mail->From = 'admin@tmt.com';
            $mail->Subject = 'Terminanfrage für Schulung: ' . $survey->traininggroup()->course()->title;
            $mail->CharSet = 'utf-8';

            $data['survey'] = $survey;
            $data['sender'] = $mail->From;
            
            $mail->Body = $this->load->view('email/email_survey_confirmation', $data, TRUE);
            $mail->AltBody = strip_tags($this->load->view('email/email_survey_confirmation', $data, TRUE));

            $mail->AddAddress($survey->employee()->contactdata()->email);
            
            if (!$mail->send())
                echo $mail->ErrorInfo;
            
        }
        return TRUE;
    }

}
